package com.example.chenjun.myapplication.net;

import android.app.Activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;

public class NetManager {
    private static volatile NetManager mManager;
    private Map<Activity, List<BaseLoader>> mLoaderMap;
    private ArrayBlockingQueue<BaseLoader> mRetryLoaderQueue;
    private NetManager(){
        mLoaderMap = new HashMap<>();
        mRetryLoaderQueue = new ArrayBlockingQueue<>(16);
    }

    public static NetManager singleTon(){
        if (mManager == null){
            synchronized (NetManager.class){
                if (mManager == null){
                    mManager = new NetManager();
                    return mManager;
                }
            }
        }
        return mManager;
    }

    public Map<Activity, List<BaseLoader>> getLoaderMap() {
        return mLoaderMap;
    }

    public void addLoader(BaseLoader loader){
        Activity activity = loader.getDialogActivity();
        List<BaseLoader> list = mLoaderMap.get(activity);
        if (list == null){
            list = new ArrayList<>();
            mLoaderMap.put(activity, list);
        }
        list.add(loader);

    }

    public void removeAtActivity(Activity activity){
        if (mLoaderMap.containsKey(activity)) {
            List<BaseLoader> loaders = mLoaderMap.get(activity);
            for (BaseLoader loader : loaders) {
                loader.cancel();
            }
            mLoaderMap.remove(activity);
        }
    }

    public void removeLoader(BaseLoader loader){
        Activity activity = loader.getDialogActivity();
        List<BaseLoader> loaders = mLoaderMap.get(activity);
        if (loaders != null && loaders.contains(loader)){
            loader.cancel();
            loaders.remove(loader);
            if (loaders.size() == 0){
                mLoaderMap.remove(activity);
            }
        }
    }

    public void addRetryLoader(BaseLoader loader){
        removeLoader(loader);
        mRetryLoaderQueue.offer(loader);
    }

    public void retry(){
        for (int i = 0; i < mRetryLoaderQueue.size(); i++) {
            BaseLoader loader = mRetryLoaderQueue.poll();
            addLoader(loader);
            loader.retry();
        }
    }

    public void retry(BaseLoader loader){
        mRetryLoaderQueue.remove(loader);
        addLoader(loader);
        loader.retry();
    }
}
